package com.huateng.springcloud.datasource;


import lombok.Data;
import org.apache.commons.pool2.ObjectPool;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.DefaultPooledObject;

import java.sql.*;


/**
 * 连接数据库
 *
 * @author Evan
 * @create 2021/7/19 16:39
 */
@Data
public class ConnectionPooledObjectFactory implements PooledObjectFactory<HTConnection> {

    private ObjectPool<HTConnection> objectPool;

    @Override
    public PooledObject makeObject() throws Exception {
        Class.forName("com.mysql.jdbc.Driver");
        Connection connection = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/test", "root", "123456");
        HTConnection htConnection = new HTConnection();
        htConnection.setConnection(connection);
        htConnection.setObjectPool(objectPool);
        return new DefaultPooledObject(htConnection);
    }

    @Override
    public void destroyObject(PooledObject<HTConnection> pooledObject) throws Exception {
        pooledObject.getObject().close();
    }

    @Override
    public boolean validateObject(PooledObject<HTConnection> pooledObject) {
        Connection connection = pooledObject.getObject();
        try {
            PreparedStatement statement = connection.prepareStatement("SELECT 1");
            ResultSet resultSet = statement.executeQuery();
            int i = resultSet.getInt(1);
            return i == 1;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public void activateObject(PooledObject pooledObject) throws Exception {
        //可以把connection额外的配置放到这里
    }

    @Override
    public void passivateObject(PooledObject<HTConnection> pooledObject) throws Exception {
        HTConnection htConnection = pooledObject.getObject();
        Statement statement = htConnection.getStatement();
        if (statement != null){
            htConnection.close();
        }
    }

}
